import routes from "uni-router-routes";
import { createRouter } from "uniapp-router-next";
import useUserStore from "@/store/modules/user";
import cache from "@/utils/cache";
import { toast, showConfirm, tansParams } from "@/utils/common";
import {
	getToken,
	setToken,
	removeToken,
	getUser,
	setUser,
	removeUser,
} from "@/utils/auth";
const BACK_URL = "back_url";
const router = createRouter({
	routes: [
		...routes,
		{
			path: '*',
			redirect() {
				return {
					name: '首页'
				};
			}
		}
	],
	debug: import.meta.env.DEV,
	//@ts-ignore
	platform: process.env.UNI_PLATFORM,
	h5: {},
});

//存储登陆前的页面
let isFirstEach = true;
router.beforeEach(async (to, from) => {
	//保存第一次进来时的页面路径（需要登陆才能访问的页面）
	if (isFirstEach) {
		const userStore = useUserStore();
		if (!userStore.isLogin && !to.meta.white) {
			cache.set(BACK_URL, to.fullPath);
		}
		isFirstEach = false;
	}
});
router.afterEach((to, from) => {
	const userStore = useUserStore();
	if (!userStore.isLogin && !to.meta.white) {
		cache.set(BACK_URL, to.fullPath);
	}
});

// 登录拦截
router.beforeEach(async (to, from) => {
	const userStore = useUserStore();
	console.log(to.meta);
	if (!getToken() && to.meta.auth) {
		console.log("触发拦截");
		showConfirm(
			"暂未登录，是否授权手机号登录?"
		).then((res) => {
			if (res.confirm) {
				uni.navigateTo({ url: "/pages/login" });
			}
		})
		return false;
	}
});

export default router;